#! /usr/bin/python

import argparse
import glob
import importlib
import os
import time
#import optparse

def Main():
    # Handle command line option
    parser = argparse.ArgumentParser(
            usage       = '%(prog)s [OPTION] [PROBLEM_NUMBER ...]',
            description = 'Solve Project Euler problem.')
    parser.add_argument('problem',
            type=int, nargs='*', metavar='PROBLEM_NUMBER',
            help='problem number to solve (default: solve all)')
    parser.add_argument('-l', '--list',
            dest='list', action='store_const', const=True, default=False,
            help='list all available problem')
    args = parser.parse_args()

    # If no problem specified, run them all
    if len(args.problem) == 0 or args.list:
        problem_file = glob.glob(os.path.join('problem', 'p???.py'))
        args.problem = [int(string[-6:-3]) for string in problem_file]

    #
    if args.list:
        for pb in args.problem:
            print 'Problem %s' % pb
        return

    # Get result
    result = []
    for pb in args.problem:
        # import pb library
        try:
            module = importlib.import_module("problem.p%03d" % pb)
        except ImportError:
            result.append((pb, "N/A", 0))
            continue

        # solve the problem
        start = time.clock()
        res = module.Solve()
        end = time.clock()

        # gather result and execution time
        result.append((pb, res, end - start))

    # Display result
    for pb, res, t in result:
        print "Problem {:>3}: {:>15} ({:<5} second)".format(pb, res, t)


if __name__ == '__main__':
    Main()

